package com.XMLReader;

import com.Bean.Context;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.Method;

public class XMLReader {

    public static Context ContextBuilder(File xml) {
        Context context = new Context();
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(xml);
            Element element = document.getDocumentElement();
            NodeList beans = element.getElementsByTagName("bean");
            System.out.println(beans.getLength());
            for (int i = 0; i < beans.getLength(); ++i) {

                Element item = (Element) beans.item(i);

                String id = item.getAttribute("id");
                String className = item.getAttribute("class");
                Class<?> beanClass = Class.forName(className);
                Object obj = beanClass.getDeclaredConstructor().newInstance();

                NodeList props = item.getElementsByTagName("property");

                for (int j = 0; j < props.getLength(); ++j) {
                    Element prop = (Element) props.item(j);
                    String valueName = prop.getAttribute("name");
                    String ref = prop.getAttribute("ref");
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(valueName, beanClass);
                    Class<?> valueClass = propertyDescriptor.getPropertyType();
                    Object value = context.getBean(ref);
                    Method setter = propertyDescriptor.getWriteMethod();
                    setter.invoke(obj, valueClass.cast(value));
                }

                context.addBean(id, obj);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return context;
    }

    private static String initStr(String old) {    // 将单词的首字母大写
        return old.substring(0, 1).toUpperCase() + old.substring(1);
    }

}
